<template>
    <div v-loading="loading" class="app-container">
        <el-steps :active="active">
            <el-step title=" " description="系统基本信息"></el-step>
            <el-step title=" " description="资源新增/修改"></el-step>
            <el-step title=" " description="清单确认"></el-step>
        </el-steps>
        <div v-if="detail">
          <AddA ref="adda" :detail="detail" @next="next" :dept="configure.dept" v-show="active == 1" />
          <AddB
              ref="addb"
              @next="next"
              :configure="configure"
              :supplierCode="detail.supplierCode"
              v-show="active == 2"
          />
          <AddC ref="addc" :configure="configure" v-show="active == 3" />
        </div>
        <!-- <Process ref="process" :ind="0" style="margin-bottom: 10px" /> -->
        <div style="display: flex; justify-content: flex-end">
            <el-button
                :loading="btnLoading"
                type="info"
                v-if="active > 1"
                @click="active--"
                >上一步</el-button
            >
            <el-button
                :loading="btnLoading"
                type="primary"
                v-if="active == 3"
                @click="ConfirmModification"
                >确认修改</el-button
            >
            <el-button
                :loading="btnLoading"
                type="primary"
                v-else
                @click="next(false)"
                >下一步</el-button
            >
            <el-button @click="ReturnSuperio">取 消</el-button>
        </div>
    </div>
</template>

<script>
import AddA from "./components/addA.vue";
import AddB from "./components/addB.vue";
import AddC from "./components/addC.vue";
// import Process from "../../todoItem/todo/process.vue";
import { resourcesChangeApply } from "@/api/resources/change.js";
import { treeselect } from "@/api/system/dept";
import { getDicts } from "@/api/system/dict/data";
import { uploadFile } from "@/api/system/upload.js";
  import {
    cloudUpDetail,
    ConfirmCloudUp,
  } from "@/api/cloud/cloud";

import {
    listByCode,
    serviceByClazz,
    classByCode,
    specEcs
} from "@/api/resources/apply";
export default {
    name: "addChangesNoXc",
    components: {
        AddA,
        AddB,
        AddC,
        // Process,
    },
    data() {
        return {
            loading:false,
            btnLoading: false,
            detail:null,
            // 申请步骤
            active: 1,
            // 表单参数
            form: {
                //系统id
                cloudUpId: "",
                //系统基本信息
                cloudUp: {},
                cloudSupplier: "", //服务商
                cloudSupplier_label: "", //服务商名称
                hosts: [], //资源列表
                databases: [], //数据库列表
                storeProducts: [], //存储产品列表
                safeProducts: [], //安全产品列表
                remark: "", //说明
                files: [], //文件
                actionName: "发起申请"
            },
           //配置
           configure:{
                dept:[],
                available_domain: [], //可用域
                cloud_service_provider: [], //服务商
                storage_type: [], //系统盘类型
                codeList: [], //云服务器规格列表
                czxtList: [], //操作系统列表
                ccList: [], //数据盘类型
                fwcpList: [], //服务型磁盘类型
                wlfwqList: [], //高性能服务器资源类型
                sjkList: [], //数据库类型
                yyaqList: [], //安全产品,
                SpecificationsList:[]
            },
            subData:null
        };
    },
    created() {
        setTimeout(()=>{
          this.$refs.adda.xzfsChange(2)
        //   this.$refs.process.init({
        //     definitionName: '资源变更',
        //     taskName: '资源变更'
        //   })
        },100)
    },
    mounted() {
      this.getcloudUpDetail(this.$route.params.Id)
        // setTimeout(()=>{
        //   this.$refs.process.init({
        //     definitionName: '资源变更',
        //     taskName: '资源变更'
        //   })
        // },100)
    },
    methods: {
      ConfirmModification(data){
          this.$confirm("是否确认修改?", "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
              }).then(() => {
                this.btnLoading=true
                  let form=JSON.parse(JSON.stringify(this.subData))
                  let obj={},
                      hosts=[],
                      storeProducts=[],
                      databases=[];
                  form.safeProductsList.forEach(item=>{
                      if(parseInt(item.num)>0){
                        delete form.safeProducts[item.productName][0].id
                        obj[item.productName]=[]
                        for(let i=0;i<item.num;i++){
                          obj[item.productName].push(form.safeProducts[item.productName][0])
                        }
                      }
                  })
                  form.hosts.forEach(item=>{
                    if(!item.insStatus||item.insStatus!='REMOVE'){
                      hosts.push(item)
                    }
                  })
                  form.storeProducts.forEach(item=>{
                    if(!item.insStatus||item.insStatus!='REMOVE'){
                      storeProducts.push(item)
                    }
                  })
                  form.databases.forEach(item=>{
                    if(!item.insStatus||item.insStatus!='REMOVE'){
                      databases.push(item)
                    }
                  })



                  form.safeProducts=obj
                  form.hosts=hosts
                  form.storeProducts=storeProducts
                  form.databases=databases
                  delete form.safeProductsList
                  ConfirmCloudUp(form).then(res=>{
                      if(res.code == 200){
                          this.$store.state.tagsView.visitedViews.splice(this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path), 1)
                          this.$destroy(this.$options.name)
                          this.$router.push('/cloud/cloudapply')
                      }
                  }).finally(res=>{
                    this.btnLoading=false
                  })
          })
      },

      //上云系统
      getcloudUpDetail(e) {
        if (e) {
          this.loading = true
          cloudUpDetail(e).then(response => {
            response.data.storeProducts.forEach(item=>{
              item.hostIds=[]
              if(item.hosts){
                item.hosts.forEach(it=>{
                  item.hostIds.push(it.id)
                })
              }
            })
            this.detail = response.data
            this.loading = false
            this.getDataOfAdd()
          })
        }
      },
        getDataOfAdd(){
            // 获取信创CPU或者内存规格
            specEcs({Inspur:this.detail.supplierCode}).then(res=>{
                this.configure.SpecificationsList = res.rows
            })
            //部门列表
            treeselect({}).then((response) => {
                this.configure.dept = response.data;
            });
            //可用域
            getDicts("available_domain").then((response) => {
                this.configure.available_domain = response.data;
            });
            //服务商
            getDicts("cloud_service_provider").then((response) => {
                this.configure.cloud_service_provider = response.data;
            });
            //盘类型
            serviceByClazz({ code: "cc",supplier:this.detail.supplierCode }).then((response) => {
                response.data.forEach((item) => {
                    if (
                        ["FCcc(tykcc)2", "FCcc_ssd", "spycc2"].indexOf(
                            item.code
                        ) < 0
                    ) {
                        this.configure.storage_type.push(item);
                    }
                    if (["spycc2"].indexOf(item.code) < 0) {
                        this.configure.ccList.push(item);
                    }
                    if (
                        ["fbscc_wjcc2", "FCcc(tykcc)2", "FCcc_ssd"].indexOf(
                            item.code
                        ) < 0
                    ) {
                        this.configure.fwcpList.push(item);
                    }
                });
            });
            //操作系统
            classByCode({ code: "czxt" }).then((response) => {
                this.configure.czxtList = response.data;
            });
            // //云服务器规格列表
            // listByCode("spec_ecs").then((response) => {
            //     this.configure.codeList = response.data;
            // });
            //高性能服务器资源类型列表
            serviceByClazz({ code: "wlfwq",supplier:this.detail.supplierCode }).then((response) => {
                this.configure.wlfwqList = response.data;
            });
            //数据库类型列表
            serviceByClazz({ code: "sjk",supplier:this.detail.supplierCode }).then((response) => {
                this.configure.sjkList = response.data;
            });
            //安全产品列表
            serviceByClazz({ code: "yyaq",supplier:this.detail.supplierCode }).then((response) => {
                this.configure.yyaqList = response.data;
            });
        },
        // 返回上级--> 资源申请列表
        ReturnSuperio(){
          try{
            this.$store.state.tagsView.visitedViews.splice(this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path), 1)
            this.$router.push(this.$store.state.tagsView.visitedViews[this.$store.state.tagsView.visitedViews.length - 1].path)
          }catch(err){
            this.$router.push('/index')
          }

        },
        //下一步
        next(data) {
          if(data){
            if (this.active == 2) {
                this.subData=data
                this.$refs.addc.init(data);
                this.active=3
            }
          }else{
            if(this.active == 1){
              this.$refs.addb.init(this.detail);
              this.active=2
            } else if (this.active == 2) {
                this.$refs.addb.next();
            }
          }
          return
            if (data) {
                if(this.active == 1){
                    this.$refs.addb.init(data);
                }
                if (this.active == 1) {
                    if (data.cloudUpId) {
                        this.form.cloudUpId = data.cloudUpId;
                    } else {
                        this.form.cloudUpId = "";
                        data.fundBySelf = data.fundBySelf == "1" ? true : false;
                        if (data.fundFromRadio == "1") {
                            data.fundFrom = "区（县）";
                        } else if (data.fundFromRadio == "2") {
                            data.fundFrom = "市级";
                        }
                    }
                    this.form.cloudUp = data;
                    this.getDataOfAdd()
                } else if (this.active == 2) {
                    this.form.cloudSupplier = data.cloudSupplier;
                    this.form.cloudSupplier_label = data.cloudSupplier_label;
                    this.form.hosts = data.hosts;
                    this.form.databases = data.databases;
                    this.form.storeProducts = data.storeProducts;
                    this.form.safeProducts = data.safeProducts;
                    this.form.remark = data.remark;
                    this.form.files = data.fileList;
                    this.form.oldform = data.oldform;
                }
                this.active++;
            } else if (this.active == 1) {
                this.$refs.adda.next();
            } else if (this.active == 2) {
                this.$refs.addb.next();
            } else {
                this.submitApply();
            }
        },
        /** 提交申请 */
        submitApply() {
            this.$confirm("是否确认提交?", "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                this.btnLoading = true;
                let form = JSON.parse(JSON.stringify(this.form));
                if (this.form.files && this.form.files.length) {
                    var param = new FormData();
                    param.append("key", "file");
                    this.form.files.forEach((item) => {
                        param.append("file", item.raw);
                    });
                    if(this.form.cloudUp.files && this.form.cloudUp.files.length && this.form.cloudUp.files[0].raw){
                        var cloudUpparam = new FormData()
                        cloudUpparam.append("key", "file");
                        this.form.cloudUp.files.forEach((item) => {
                            cloudUpparam.append("file", item.raw);
                        });
                        uploadFile(cloudUpparam).then(ress=>{
                            form.cloudUp.files = ress.data
                            uploadFile(param)
                            .then((res) => {
                                form.files = res.data;
                                form.actionName = '发起申请'
                                this.sub(form);
                            })
                            .catch((e) => {
                                this.btnLoading = false;
                            });
                        })
                        .catch((e) => {
                            this.btnLoading = false;
                        });

                    }else{
                        uploadFile(param)
                        .then((res) => {
                            form.files = res.data;
                            form.actionName = '发起申请'
                            this.sub(form);
                        })
                        .catch((e) => {
                            this.btnLoading = false;
                        });
                    }
                } else {
                    if(this.form.cloudUp.files && this.form.cloudUp.files.length && this.form.cloudUp.files[0].raw){
                        var cloudUpparam = new FormData()
                        cloudUpparam.append("key", "file");
                        this.form.cloudUp.files.forEach((item) => {
                            cloudUpparam.append("file", item.raw);
                        });
                        uploadFile(cloudUpparam)
                            .then((res) => {
                                form.cloudUp.files = res.data
                                form.actionName = '发起申请'
                                this.sub(form);
                            })
                            .catch((e) => {
                                this.btnLoading = false;
                            });
                    }else{
                        form.actionName = '发起申请'
                        this.sub(form);
                    }
                }
            });
        },
        sub(form) {
            let data={cloudUpId:form.cloudUp.id,remark:form.remark,cloudUp:form.cloudUp,files : form.files,
                      hosts:[],databases:[],storeProducts:[],safeProducts:[]}
            form.hosts.forEach(item=>{
              item.insId=item.id
            //   delete item.id
              if(item.osDisk){
                item.osDisk.insId=item.osDisk.id
                // delete item.osDisk.id
              }
              item.disks.forEach(it=>{
                it.insId=it.id
                // delete it.id
              })
              data.hosts.push({changeTo:item})
            })
            form.databases.forEach(item=>{
              item.insId=item.id
            //   delete item.id
              data.databases.push({changeTo:item})
            })
            form.storeProducts.forEach(item=>{
              item.insId=item.id
            //   delete item.id
              data.storeProducts.push({changeTo:item})
            })
            form.safeProducts.forEach(item=>{
              item.insId=item.id
            //   delete item.id
              data.safeProducts.push({changeTo:item})
            })
            data.isXc = false
            resourcesChangeApply({ formObject: data })
                .then((res) => {
                    this.$message({
                        message: "提交成功",
                        type: "success",
                    });
                    this.$store.state.tagsView.visitedViews.splice(this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path), 1)
                    this.$router.push('/resources/change')
                })
                .finally(() => {
                    this.btnLoading = false;
                });
        },
    },
};
</script>
